<template>
  <div>
    <!-- 目标及完成情况分析 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle"
      @resetChange="resetChange"
      :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables ref="table" :columns="columns" :fetchapi="fetchApi" :params="fetchParams" :datakey="'records'"
        columnsRef="zjvehicleMaterials" :onRowSelectChange="selectChangeHandle" :isSelectColumn="false"
        :onColumnsChange="columns => (this.columns = columns)">
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" @click="addHandle(4)">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

  </div>
</template>
<script>
import moment from 'moment';
import {queryList,exportList , getSeriesList, getModelList} from '@/api/omSaleP/salesPlan/GoalAccomplished';
import { dictionary } from '@/utils/dictMixin';
import { region } from '@/api/cms-common/region';
import { exportExcelFile } from '@/utils';
import { getSaleAreaInfo  } from '@/api/cms-common/dealerdata/index';
export default {
  name: 'GoalAccomplished',
  components: {
  },
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
        xhrAbort: false,
        targetDate:moment().format('YYYY-MM')
      },
      formData: {},
      exportLoading: false,
      visible: false,
      addvisible: false,
      IssueVisible: false,
      orderVisible: false,
      isOpen: true,
      selectList: [],
      isIssue: true,
      importVisible: false
    };
  },
  mixins: [dictionary,region],
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.initProvince();
    this.getSeriesData();
    this.getAreaData();
  },
  methods: {
    async getAreaData() {
      const res = await getSaleAreaInfo(15061015);
      if (res.resultCode === 200) {
        this.areaList = res.data;
        res.data.map((x) => {
          this.topFilterList.find((item) => item.fieldName === 'areaId').itemList.push({ text: x.orgName, value: x.id });
        });
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = this.createRegionList();
      this.topFilterList.find((item) => item.fieldName == 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      //清空市
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = cl;
    },
    //初始化车型
    async initModel(seriesId) {
      this.topFilterList.find((item) => item.fieldName == 'modelId').itemList = [];
      this.topFilterList.find((item) => item.fieldName == 'modelId').initialValue = '';
      if (!seriesId) {
        return;
      }
      const res = await getModelList({ seriesId: seriesId });
      if (res.resultCode === 200) {
        res.data.map((x) => {
          this.topFilterList.find((item) => item.fieldName == 'modelId').itemList.push({ text: x.modelName, value: x.modelId });
        });
      }
    },
    async getSeriesData() {
      const res = await getSeriesList();
      if (res.resultCode === 200) {
        res.data.map((x) => {
          this.topFilterList.find((item) => item.fieldName == 'seriesId').itemList.push({ text: x.seriesName, value: x.seriesId });
        });
      }
    },
    resetChange(params) {
      this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'cityId').itemList = [];
      this.$refs.TopFilter.RESET_FORM();
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    createdFrom() {
      return [
        {
          type: 'DATE',
          label: '指标月份',
          fieldName: 'targetDate',
          initialValue: moment().format('YYYY-MM'),
          dateType: 'month',
          clearable: true,
        },
        // {
        //   type: 'SELECT',
        //   label: '状态',
        //   fieldName: 'status',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('2132'),
        // },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesId',
          placeholder: '请选择',
          itemList: [],
          change: (value) => {
            this.initModel(value);
          },
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          placeholder: '请选择',
          itemList: [],
          change: (value) => {
            this.initCity(value);
          },
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          placeholder: '请选择',
          itemList: [],
          // change: (value) => {
          //   this.initTown(value)
          // },
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            //编码转汉字
            return <span>{this.createDictText(props.row.status, '2132')}</span>;
          },
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '指标月份',
          dataIndex: 'targetDate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '任务数量（结算）',
          dataIndex: 'targetNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '完成数量（结算）',
          dataIndex: 'targetNumCompletion',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '完成率（结算）',
          dataIndex: 'targetNumCompletionRate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '任务数量（终端）',
          dataIndex: 'targetRetailNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '完成数量（终端）',
          dataIndex: 'targetRetailNumCompletion',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '完成率（终端）',
          dataIndex: 'targetRetailNumCompletionRate',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
    async addHandle(type) {
       if (type == 4) {
        // this.$router.push('/admin/auth/oem/downloadCenter');
        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            let json = this.fetchParams;
            this.exportLoading = true;
            exportList(json)
              .then(response => {
                exportExcelFile(response.data, '目标及完成情况分析');
                this.exportLoading = false;
              })
              .catch(err => {
 
              });
          })
          .catch(() => {
 
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
      } else {
        this.importVisible = true;
      }
    },
    selectChangeHandle(row) {
      if (row.length > 0) {
        this.selectList = row;
        this.isOpen = false;
        // let is = false;
        // row.map(x => {
        //   if (x.isIssue == 10041001) {
        //     is = true;
        //   }
        // });
        // this.isIssue = is ? true : false;
      } else {
        this.selectList = [];
        this.isOpen = true;
        // this.isIssue = true;
      }
    },
    changeHandle(params) {
      this.isOpen = true;
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    editHandle(data) {
      this.formData = data;
      this.visible = true;
    },
    addcloseHandler(val) {
      this.addvisible = false;
      this.isOpen = true;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    emitcloseHandler(val) {
      this.visible = false;
      this.isOpen = true;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    ordercloseHandler() {
      this.orderVisible = false;
      this.isOpen = true;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    // async getUser() {
    //   let res = await getDealerUser();
    //   let empList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    //   this.columns.find(item => item.dataIndex === 'updatedBy').editItems = empList; //操作姓名
    //   this.columns.find(item => item.dataIndex === 'updatedBy').filterItems = empList;
    // },
    importcloseHandler() {
      this.importVisible = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    }
  }
};
</script>
